<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\promotion;


use app\common\model\bookpack\Bookpack;
use app\common\model\click\BdClick;
use app\common\model\click\KsClick;
use app\common\model\click\UcClick;
use app\common\model\click\VivoClick;
use app\common\model\media\Media;
use app\common\model\media_account\MediaAccount;
use app\common\model\promotion\PromotionLink;
use app\common\logic\BaseLogic;
use app\common\model\quickapp\Quickapp;
use app\common\model\recharge_template\RechargeTemplate;
use app\common\model\return_rule\ReturnRule;
use app\common\service\media\MediaService;
use think\facade\Db;


/**
 * PromotionLink逻辑
 * Class PromotionLinkLogic
 * @package app\adminapi\logic
 */
class PromotionLinkLogic extends BaseLogic
{


    /**
     * 添加推广链
     *
     * @param array $params
     * @return bool|string
     */
    public static function add(array $params)
    {
        if (!$platform = $params['platform'] ?? 0) {

            return '请选择快应用';
        }
        $bookpackType = $params['bookpack_type'] ?? 0;
        // 是否有推广书包
        if ($params['bookpack_type'] ?? 0) {
            if (!Bookpack::where('platform', $platform)->where('bookpack_type', $bookpackType)->findOrEmpty()) {

                return '请先配置推广快应用的相应的书包配置';
            }
        }

        Db::startTrans();
        try {
            $result       = PromotionLink::create([
                'platform'             => $platform,
                'admin_id'             => $params['admin_id'],
                'name'                 => $params['name'],
                'paytype'              => $params['paytype'],
                'egold'                => $params['egold'],
                'add_desktop_type'     => $params['add_desktop_type'],
                'add_desktop_id'       => $params['add_desktop_id'],
                'recharge_template_id' => $params['recharge_template_id'],
                'bookpack_type'        => $params['bookpack_type'] ?? 1,
                'follow_chapters'      => $params['follow_chapters'] ?? 0,
                'book_id'              => $params['book_id'],
                'chapter_id'           => $params['chapter_id'],
                'book_name'            => $params['book_name'],
                'media'                => $params['media'],
                'chapter_name'         => $params['chapter_name'],
                'remark'               => $params['remark'] ?? '',
                'audit_mode'           => $params['audit_mode'],
                'media_feedback'       => $params['media_feedback'],
            ]);
            $package_name = Quickapp::where('id', $params['platform'])->value('package_name');
            $data         = self::getUrl($result->id, $package_name, $params);
            PromotionLink::where('id', $result->id)->update($data);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * 获取推广链接
     *
     * @param $linkId
     * @param $media
     * @param $packageName
     * @param $params
     * @return array
     */
    public static function getUrl($linkId, $packageName, $params)
    {
        $media = $params['media'] ?? 0;

        $uri = 'book_id=' . $params['book_id'] . '&chapter_id=' . $params['chapter_id'] . '&promotion_link_id=' . $linkId . '&source=' . $media;

        $hapUrl = $packageName . '?' . $uri;

        switch ($media) {
            case Media::SOURCE_JL :
                return [
                    'hap_url'         => $hapUrl,
                    'custom_http_url' => config('project.jl_monitoring_link') . '&' . $uri,
                ];
            case Media::SOURCE_UC :
                return [
                    'hap_url'         => $hapUrl,
                    'custom_http_url' => config('project.uc_monitoring_link') . '&' . $uri,
                ];
            case Media::SOURCE_KS :
                return [
                    'hap_url'         => $hapUrl . '&callback=__CALLBACK__',
                    'custom_http_url' => config('project.ks_monitoring_link') . '&' . $uri,
                ];
            case Media::SOURCE_BD :
                return [
                    'hap_url'         => $hapUrl,
                    'custom_http_url' => config('project.bd_monitoring_link') . '&' . $uri,
                ];
            case Media::SOURCE_OPPO :
                return [
                    'hap_url'         => $hapUrl,
                    'custom_http_url' => config('project.oppo_monitoring_link') . '&' . $uri,
                ];
            case Media::SOURCE_VIVO :
                return [
                    'hap_url'         => $hapUrl,
                    'custom_http_url' => config('project.vivo_monitoring_link') . '&' . $uri,
                ];
            default :
                return [];
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            PromotionLink::where('id', $params['id'])->update([
                'paytype'              => $params['paytype'],
                'egold'                => $params['egold'],
                'add_desktop_type'     => $params['add_desktop_type'],
                'add_desktop_id'       => $params['add_desktop_id'],
                'recharge_template_id' => $params['recharge_template_id'],
                'bookpack_type'        => $params['bookpack_type'] ?? 1,
                'follow_chapters'      => $params['follow_chapters'] ?? 0,
                'remark'               => $params['remark'] ?? '',
                'audit_mode'           => $params['audit_mode'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public static function delete(array $params): bool
    {
        return PromotionLink::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/03/04 19:26
     */
    public static function detail($params): array
    {
        $field  = 'id,name,paytype,egold,add_desktop_type,add_desktop_id,recharge_template_id,bookpack_id,bookpack_type,follow_chapters,book_id,book_name,chapter_id,chapter_name,media,audit_mode,hap_url,http_url,custom_http_url';
        $result = PromotionLink::field($field)->findOrEmpty($params['id'])->toArray();
        //type=1 复制推广链
        $type = $params['type'] ?? 0;
        if ($type == 1) {
            $returnRule = ReturnRule::where('promotion_link_id', $params['id'])->findOrEmpty();
            if ($returnRule->isEmpty()) {
                self::setError('请先绑定回传规则');
                return [];
            }
            $mediaAccount = MediaAccount::where('promotion_link_id', $params['id'])->findOrEmpty();
            if ($mediaAccount->isEmpty()) {
                self::setError('请先绑定媒体账户');
                return [];
            }
            if ($result['media'] == Media::SOURCE_VIVO) {
                if (empty($mediaAccount->src_id)) {
                    self::setError('请先vivo事件源ID');
                    return [];
                }
            }
        }

        $result['recharge_template_name'] = RechargeTemplate::where('id', $result['recharge_template_id'])->value('name') ?? '';
        $result['bookpack_name']          = Bookpack::where('id', $result['bookpack_id'])->value('name') ?? '';
        return $result;
    }


    /**
     * 联调测试
     *
     * @param $id
     * @param $type
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function joinTest($id, $type)
    {
        if (!$id || !$type) {

            return false;
        }

        $link = PromotionLink::where('id', $id)->findOrEmpty();
        if ($link->isEmpty()) {

            return false;
        }
        $media = $link->media;
        switch ($media) {
            case Media::SOURCE_BD :
                $click = BdClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                $callback = $click->callback_url ?? '';
                if (!$callback) {

                    return false;
                }
                $isReturn = false;
                if ($click->oaid && $click->oaid != 'NULL' && $click->oaid != '__OAID__') {
                    $joiType  = 'oaid';
                    $isReturn = true;
                }
                if ($click->imei_md5 && $click->imei_md5 != 'NULL' && $click->imei_md5 != '__IMEI_MD5__') {
                    $joiType  = 'imei';
                    $isReturn = true;
                }
                if ($click->ip && $click->ip != '__IP__') {
                    $joiType  = 'ip';
                    $isReturn = true;
                }
                if ($isReturn) {
                    if ($type == 1) {
                        MediaService::BdReturn(['user_id' => '百度应用调起联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_DEEPLINK);
                        return MediaService::BdReturn(['user_id' => '百度激活联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_ACTIVE);
                    }
                    if ($type == 2) {
                        return MediaService::BdReturn(['user_id' => '百度加桌联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_ADD_DESKTOP);
                    }
                    if ($type == 3) {
                        return MediaService::BdReturn(['user_id' => '百度付费联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_PAYMENT);
                    }
                    if ($type == 4) {
                        return MediaService::BdReturn(['user_id' => '百度关键行为联调测试'], $joiType, $click->callback_url, MediaService::BD_TYPE_ACTION);
                    }
                }
                return false;
            case Media::SOURCE_KS :
                $click = KsClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                $callback = $click->callback ?? '';
                if (!$callback) {

                    return false;
                }
                if ($type == 1) {
                    return MediaService::KsReturn(['user_id' => '快手激活联调测试'], $callback, MediaService::KS_TYPE_ACTIVE);
                }
                if ($type == 2) {
                    return MediaService::KsReturn(['user_id' => '快手加桌联调测试'], $callback, MediaService::KS_TYPE_REGISTER);
                }
                if ($type == 3) {
                    return MediaService::KsReturn(['user_id' => '快手付费联调测试'], $callback, MediaService::KS_TYPE_PAYMENT, 10);
                }
                if ($type == 4) {
                    return MediaService::KsReturn(['user_id' => '快手关键行为联调测试'], $callback, MediaService::KS_TYPE_PAYMENT);
                }
                return false;
            case Media::SOURCE_UC :
                $click = UcClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                $callback = $click->callback_url ?? '';
                if ($type == 1) {
                    return MediaService::UcReturn(['user_id' => 'UC激活联调测试'], $callback, MediaService::UC_TYPE_ACTIVE);
                }
                if ($type == 2) {
                    return MediaService::UcReturn(['user_id' => 'UC加桌联调测试'], $callback, MediaService::UC_TYPE_ADD_DESKTOP);
                }
                if ($type == 3) {
                    MediaService::UcReturn(['user_id' => 'UC快应用付费联调测试'], $callback, MediaService::UC_TYPE_PAYMENT);
                    return MediaService::UcReturn(['user_id' => 'UC付费联调测试'], $callback, MediaService::UC_TYPE_PAY);
                }
                return false;
            case Media::SOURCE_VIVO :
                $click = VivoClick::where('promotion_link_id', $id)->order('id', 'desc')->findOrEmpty();
                if ($click->isEmpty()) {

                    return false;
                }
                if ($type == 1) {
                    return MediaService::VivoReturn(['user_id' => 'VIVO激活联调测试'], $click, MediaService::VIVO_TYPE_ACTIVE);
                }
                if ($type == 2) {
                    return MediaService::VivoReturn(['user_id' => 'VIVO加桌联调测试'], $click, MediaService::VIVO_TYPE_ADD_DESKTOP);
                }
                if ($type == 3) {
                    return MediaService::VivoReturn(['user_id' => 'VIVO付费联调测试'], $click, MediaService::VIVO_TYPE_PAYMENT, 10);
                }
            default:
                return false;
        }
    }
}
